import { createEf } from '@/utils/ef'
import { gsap } from 'gsap'
import { getPixi, getPixiData, getData } from '@/store/modules/usePixiStore'
import useMainStore from '@/store/modules/useMainStore'
import useSearchStore from '@/store/modules/useSearchStore'
import useModalStore from '@/store/modules/useModalStore'
import useDiyStore from '@/store/modules/useDiyStore'
import { useWindowSize } from '@vueuse/core'
import * as PIXI from 'pixi.js'
import { exportCard, exportJson } from '@/utils/export'
import { getColorMatrix } from '@/store/modules/useFilterStroe'
import { bottomParams, modalParams, diyParams } from './params'

const mainStore = useMainStore()
const searchStore = useSearchStore()
const modalStore = useModalStore()
const diyStore = useDiyStore()
const { height } = useWindowSize()
const { scale } = mainStore.getAppAttr

/** 卡册滚动翻页事件*/
export const wheelBottom = (() => {
  return createEf(
    event => {
      const sign = Math.sign(event.deltaY)
      searchStore.setCurrent(searchStore.current + sign * Math.floor(Math.abs(event.deltaY) / 100))
    },
    {
      type: 'wheel',
      peimi: true,
    },
  )
})()

/** 卡册按下事件*/
export const mousedownBottom = (() => {
  return createEf(
    event => {
      if (bottomParams.quiet) {
        const cardSetsContainer = getPixi('cardSets')
        bottomParams.origin.x = event.clientX
        bottomParams.origin.y = event.clientY
        bottomParams.origin.positionX = cardSetsContainer.position.x
        bottomParams.origin.positionY = cardSetsContainer.position.y
        bottomParams.bottomMouseDown = true
        // mousemoveBottom.on()
      }
    },
    {
      type: 'mousedown',
      peimi: true,
      finish: event => {
        const displacement = event.clientY - bottomParams.origin.y
        if (searchStore.current !== 1 && displacement > 80) {
          searchStore.subtract()
        } else if (searchStore.current !== searchStore.total && displacement < -80) {
          searchStore.add()
        } else {
          // 不翻页则还原状态
          const cardSetsContainer = getPixi('cardSets')
          const bottomHeight = height.value / scale - 114 - 30
          gsap.to(cardSetsContainer.position, {
            duration: 0.3,
            y: -(searchStore.current - 1) * bottomHeight,
          })
        }
        bottomParams.bottomMouseDown = false // 关闭状态
        // 拖拽距离过大则阻止卡牌点击事件
        if (Math.abs(displacement) > 10) {
          cardClick.stop()
        }
      },
    },
  )
})()

/** 翻页按钮向上点击事件 */
export const pageUpButtonClick = (() => {
  return createEf(
    () => {
      searchStore.subtract()
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

/** 翻页按钮向下点击事件 */
export const pageDownButtonClick = (() => {
  return createEf(
    () => {
      searchStore.add()
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

// 模态框
export const modalClick = (() => {
  return createEf(
    () => {
      const { app } = mainStore
      const cardData = getData(modalStore.cardUid)
      const cardContainer = cardData._convertContainer
      const pixiContainer = cardData._container
      // 卡牌全局坐标
      const globalPosition = pixiContainer.toGlobal(app!.stage)
      // 添加动画
      gsap.to(cardContainer.scale, { duration: modalParams.duration, x: 0.7, y: 0.7 })
      gsap.to(cardContainer.position, {
        duration: modalParams.duration,
        x: globalPosition.x / scale,
        y: globalPosition.y / scale,
        onComplete: () => {
          cardContainer.visible = false
          modalStore.setVisible(false)
        },
      })
      //
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

/** 卡牌下载事件*/
export const downloadClick = (() => {
  return createEf(
    () => {
      if (modalStore.cardUid !== -1) {
        const cardData = getData(modalStore.cardUid)
        exportCard(cardData._convertContainer, cardData.name)
      }
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

/** 卡牌点击事件 */
export const cardClick = (() => {
  return createEf(
    event => {
      // 避免翻页过程中点击了卡牌
      if (bottomParams.quiet) {
        modalStore.setVisible(true, event.target.uid) // 展示图片的uid
        const mainStore = useMainStore()
        const { app } = mainStore
        const modalContainer = getPixi('modal')
        // 卡牌全局坐标
        const globalPosition = event.target.toGlobal(app!.stage)
        const cardData = getData(event.target.uid)
        let container = cardData._convertContainer
        if (!container) {
          container = new PIXI.Container()
          // 将卡牌转换为纹理, 创建新的精灵, 并添加到模态框中
          const sprite = new PIXI.Sprite(app!.renderer.textureGenerator.generateTexture(event.target))
          container.addChild(sprite)
          sprite.anchor.set(0.5)
          container.position.set(globalPosition.x / scale, globalPosition.y / scale)
          container.scale.set(0.7) // 原大小
          modalContainer.addChild(container) // 添加到模态框中
          cardData._convertContainer = container // 保存卡牌
        } else {
          container.visible = true // 卡牌可见
        }
        // 添加动画
        gsap.to(container.scale, { duration: modalParams.duration, x: modalParams.scale, y: modalParams.scale })
        gsap.to(container.position, { duration: modalParams.duration, x: modalContainer.width / 2, y: modalContainer.height / 2 })
      }
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

// 切换按钮
export const cutBtnMouseDown = (() => {
  return createEf(
    () => {
      bottomParams.onCutBtn = true
      const colorMatrixFilter = getColorMatrix('cutBtn')[0]
      colorMatrixFilter.brightness(0.8, false)
    },
    {
      type: 'mousedown',
      peimi: true,
      finish: () => {
        bottomParams.onCutBtn = false
        const colorMatrixFilter = getColorMatrix('cutBtn')[0]
        colorMatrixFilter.brightness(1, false)
      },
    },
  )
})()

// 创作按钮
export const creationMouseDown = (() => {
  return createEf(
    () => {
      bottomParams.onCreation = true
      const colorMatrixFilter = getColorMatrix('creation')[0]
      colorMatrixFilter.brightness(0.8, false)
    },
    {
      type: 'mousedown',
      peimi: true,
      finish: () => {
        bottomParams.onCreation = false
        const colorMatrixFilter = getColorMatrix('creation')[0]
        colorMatrixFilter.brightness(1, false)
      },
    },
  )
})()

// diy模态框关闭按钮
export const closeDiyModal = (() => {
  return createEf(
    () => {
      // diyStore.setVisible(false) // TODO A
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

// diy品阶切换按钮
export const diyRankClick = (() => {
  return createEf(
    event => {
      const pixiData = getPixiData(event.target.uid)
      diyStore.creationData.rank = pixiData.key as string
    },
    { type: 'click', peimi: true },
  )
})()

// diy类型切换按钮
export const diyTypeClick = (() => {
  return createEf(
    event => {
      const pixiData = getPixiData(event.target.uid)
      diyStore.creationData.type = pixiData.key as string
    },
    { type: 'click', peimi: true },
  )
})()

// diy类别切换按钮
export const diyCategoryClick = (() => {
  return createEf(
    event => {
      const pixiData = getPixiData(event.target.uid)
      diyStore.creationData.category = pixiData.key as string
    },
    { type: 'click', peimi: true },
  )
})()

// diy元素切换按钮
export const diyElementClick = (() => {
  return createEf(
    event => {
      const pixiData = getPixiData(event.target.uid)
      diyStore.creationData.element = pixiData.key as string
    },
    { type: 'click', peimi: true },
  )
})()

// diy系列切换按钮
export const diySeriesClick = (() => {
  return createEf(
    event => {
      const pixiData = getPixiData(event.target.uid)
      diyStore.creationData.series = pixiData.key as string
    },
    { type: 'click', peimi: true },
  )
})()

// diy打开文本框
export const diyOpenInputClick = (() => {
  return createEf(
    event => {
      const container = getPixi(event.target.uid)
      const bounds = container.getBounds()
      const pixiData = getPixiData(event.target.uid)
      const text = getPixi(pixiData.textUid) as PIXI.Text
      diyStore.textSource = text.uid
      mainStore.nInput?.init(text.text, {
        top: bounds.y + 'px',
        left: bounds.x + 'px',
        width: bounds.width + 'px',
        height: bounds.height + 'px',
      })
    },
    { type: 'click', peimi: true },
  )
})()
// diy打开多行文本框
export const diyOpenTextareaClick = (() => {
  return createEf(
    event => {
      const container = getPixi(event.target.uid)
      const bounds = container.getBounds()
      const pixiData = getPixiData(event.target.uid)
      const text = getPixi(pixiData.textUid) as PIXI.Text
      diyStore.textSource = text.uid
      mainStore.nTextarea?.init(text.text, {
        top: bounds.y + 'px',
        left: bounds.x + 'px',
        width: bounds.width + 'px',
        height: bounds.height + 'px',
      })
    },
    { type: 'click', peimi: true },
  )
})()
// diy打开图片文件选择
export const diyNFileClick = (() => {
  return createEf(
    () => {
      mainStore.nFile!.choseFile((result: string) => {
        diyStore.creationData.picture = result
        diyStore.improtData = false
      })
    },
    { type: 'click', peimi: true },
  )
})()
// diy图片缩放
export const wheelDiyPicture = (() => {
  return createEf(
    event => {
      const container = getPixi(diyStore.imageUid)
      const sprite = container.children[0] as PIXI.Sprite
      if (sprite) {
        const scale = (sprite.scale.x * 10000 - event.deltaY) / 10000
        sprite.scale.set(Math.max(scale, diyStore.creationData.transform.minScale))
        const px = sprite.position.x
        const py = sprite.position.y
        const absX = (sprite.width - 292) / 2
        const absY = (sprite.height - 292) / 2
        if (px > absX) {
          sprite.position.x = absX
        } else if (px < -absX) {
          sprite.position.x = -absX
        }
        if (py > absY) {
          sprite.position.y = absY
        } else if (py < -absY) {
          sprite.position.y = -absY
        }
      }
    },
    { type: 'wheel', peimi: true },
  )
})()
// diy图片按下
export const mousedownDiyPciture = (() => {
  return createEf(
    event => {
      const container = getPixi(diyStore.imageUid)
      const sprite = container.children[0] as PIXI.Sprite
      if (sprite) {
        diyParams.onMouseDown = true
        diyParams.origin.x = event.clientX
        diyParams.origin.y = event.clientY
        diyParams.origin.positionX = sprite.position.x
        diyParams.origin.positionY = sprite.position.y
        wheelDiyPicture.off() // 点击的时候不能缩放
      }
    },
    {
      type: 'mousedown',
      peimi: true,
      finish: () => {
        diyParams.onMouseDown = false
        wheelDiyPicture.on() // 恢复缩放
      },
    },
  )
})()

// 数据导出
export const clickDataExport = (() => {
  return createEf(
    () => {
      // 导出前保存一下位置信息
      const container = getPixi(diyStore.imageUid)
      const sprite = container.children[0] as PIXI.Sprite
      if (sprite) {
        diyStore.creationData.transform.scale = sprite.scale.x
        diyStore.creationData.transform.x = sprite.position.x
        diyStore.creationData.transform.y = sprite.position.y
      }
      exportJson(diyStore.creationData)
    },
    {
      type: 'click',
      peimi: true,
    },
  )
})()

// 数据导入
export const clickDataImport = (() => {
  return createEf(
    () => {
      mainStore.nJsonFile!.choseFile((result: string) => {
        diyStore.creationData = Object.assign(diyStore.getReset(), JSON.parse(result as string))
        diyStore.improtData = true
      })
    },
    { type: 'click', peimi: true },
  )
})()

// diy图片下载
export const clickDiyDownload = (() => {
  return createEf(
    () => {
      const container = getPixi('diy-container')
      exportCard(container, diyStore.creationData.name)
    },
    { type: 'click', peimi: true },
  )
})()

// diy数据重置
export const clickDiyReset = (() => {
  return createEf(
    () => {
      diyStore.reset()
    },
    { type: 'click', peimi: true },
  )
})()

// diy字号调节减
export const clickDiyAbilityFontSizeLeft = (() => {
  return createEf(
    () => {
      diyStore.creationData.param.abilityFontSize--
    },
    { type: 'click', peimi: true },
  )
})()
// diy字号调节减
export const clickDiyAbilityFontSizeRight = (() => {
  return createEf(
    () => {
      diyStore.creationData.param.abilityFontSize++
    },
    { type: 'click', peimi: true },
  )
})()
